Collection Data Types are implemented as Structures and allow us to group multiple items of the same Data Type.
● Array Data Type holds ordered elements of same Data Type where each Element has unique integer Key
● Set Data Type holds unordered elements of same Data Type where each Element is unique
● Dictionary Data Type holds unordered elements of same Data Type where each Element has unique Key
Array Data Type is an ordered container that holds elements of the same data type.
Each Element has unique integer Key starting from 0. It can be created with Array Literal.
Array of Strings [R] [R]
// DECLARE ARRAY
var people : Array<String> = [] //Declare empty Array of Strings.
var people : [String] = ["ZERO", "FIRST"] //Declare Array of Strings. Initilize it with elements.
var people = ["ZERO", "FIRST"] //Declare Array. Data Type is implied by Array Literal.
// ADD/REMOVE ELEMENTS
people.append("SECOND") //Append element at the end of Array
people.append("THIRD") //Append element at the end of Array
people.insert("NEW" , at:2) //Insert element at index 2. Others are shifted.
people.insert("SUB ZERO", at:0) //Insert element at the begining of Array
people.remove(at:2) //Remove element at index 2. Others are shifted.
// GET/REPLACE ELEMENT
let element = people[2] //Read element at index 2
people[2] = "NEW PERSON" //Replace element at index 2
// ANALYZE
if(people.isEmpty) { print("Array is empty." ) }
var numberOfElements = people.count //5
// ITERATE THROUGH ARRAY
for person in people { print(person) }
for person in people.reversed() { print(person) }
for (index, person) in people.enumerated() { print("\(index) - \(person)") }
// PRINT ARRAY
print(element)
print(people) //["SUB ZERO", "ZERO", "FIRST", "NEW", "THIRD"]
dump (people) //Print Array